package com.gitee.qdbp.general.common.biz.sms.service;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.general.common.api.sms.model.ISmsTemplate;
import com.gitee.qdbp.general.common.biz.sms.service.dayu.model.SendSmsRequest;
import com.gitee.qdbp.general.common.biz.sms.service.dayu.model.SendSmsResponse;
import com.gitee.qdbp.general.common.error.GeneralErrorCode;

/**
 * 阿里大于短信服务<br>
 * https://help.aliyun.com/document_detail/55284.html<br>
 * <pre>
 * JAR依赖:
 * &lt;dependency&gt;
 *     &lt;groupId&gt;com.aliyun&lt;/groupId&gt;
 *     &lt;artifactId&gt;aliyun-java-sdk-core&lt;/artifactId&gt;
 * &lt;/dependency&gt;
 * </pre>
 *
 * @author zhaohuihua
 * @version 170804
 */
//  @Service // 这个Service在spring的xml文件中配置, 因为有些平台不需要短信功能
public class AliyunSmsService extends BaseSmsService {

    private static final Logger log = LoggerFactory.getLogger(AliyunSmsService.class);

    public AliyunSmsService() {
        this.properties = "settings/sms/sms.aliyun.txt";
    }

    @Override
    @PostConstruct
    public void init() {
        super.init();
    }

    @Override
    public String send(String phone, ISmsTemplate template, Object... args) throws ServiceException {

        utils.check(phone, template.name());

        String msg = "Failed to send Short Message. ";

        String[] placeholder = config.getArray("template." + template.name() + ".params", false);
        if (placeholder == null) {
            placeholder = new String[0];
        }
        if (args.length < placeholder.length) {
            log.error(msg + " The number of parameters is not enough.");
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR);
        }

        String appkey = config.getString("auth.appkey");
        String secret = config.getString("auth.secret");
        String signature = config.getString("sms.signature");
        String code = config.getString("template." + template.name());

        String regionId = config.getString("sms.region.id");

        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < placeholder.length && i < args.length; i++) {
            map.put(placeholder[i], String.valueOf(args[i]));
        }
        String params = JSON.toJSONString(map);

        // 设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", config.getString("net.client.connect.timeout"));
        System.setProperty("sun.net.client.defaultReadTimeout", config.getString("net.client.read.timeout"));
        // 初始化ascClient需要的几个参数
        final String product = config.getString("sms.service.product"); // 短信API产品名称
        final String domain = config.getString("sms.service.domain"); // 短信API产品域名
        // 初始化ascClient,暂时不支持多region
        IClientProfile profile = DefaultProfile.getProfile(regionId, appkey, secret);
        try {
            DefaultProfile.addEndpoint(regionId, regionId, product, domain);
        } catch (Exception e) {
            log.error(msg + e.toString(), e);
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR, e);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // 组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        // 使用POST提交
        request.setMethod(MethodType.POST);
        // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,
        // 批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumbers(phone);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(signature);
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(code);
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时
        // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求
        // 比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParam(params);
        // 可选-上行短信扩展码(无特殊需求用户请忽略此字段)
        // request.setSmsUpExtendCode("90997");
        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        // request.setOutId("yourOutId");
        // 请求失败这里会抛ClientException异常
        SendSmsResponse response;
        try {
            response = acsClient.getAcsResponse(request);
        } catch (Exception e) {
            log.error(msg + e.toString(), e);
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR, e);
        }

        String success = config.getString("resultcode.success");
        String resultCode = response.getCode();
        if (success.equals(resultCode)) {
            // 请求成功
            if (log.isTraceEnabled()) {
                String txt = "Send Short Message success. phone:{}, template:{}, params:{}.\n\t{}";
                String resultString = JSONObject.toJSONString(response);
                log.info(txt, phone, template, params, resultString);
            }
            return response.getBizId();
        } else {
            String txt = "Send Short Message error. phone:{}, template:{}, params:{}. result[{}:{}].\n\t{}";
            String resultMessage = config.getString("resultcode." + resultCode, false);
            String resultString = JSONObject.toJSONString(response);
            log.error(txt, phone, template, params, resultCode, resultMessage, resultString);
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR);
        }
    }

    @Override
    public Double balances() throws ServiceException {
        throw new ServiceException(ResultCode.UNSUPPORTED_OPERATION);
    }

}
